package com.mingqijia.gassafety.job.job.message;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mingqijia.gassafety.db.entity.*;
import com.mingqijia.gassafety.db.entity.vo.HistoryAlarmVo;
import com.mingqijia.gassafety.db.entity.vo.HistoryBrokenVO;
import com.mingqijia.gassafety.db.mapper.*;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.utils.RedisCacheExt;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.mingqijia.gassafety.shared.constant.Constants.IS_DELETED_FALSE;

/**
 * @author mby
 * @version 1.0.0
 * @ClassName CreateServiceInfoHistoryJob.java
 * @Description TODO
 * @createTime 2024年01月16日
 */
@Component
@Slf4j
public class RepairDataJob {

    @Autowired
    RedisCacheExt redisUtil;
    @Autowired
    HistoryAlarmMapper historyAlarmMapper;
    @Autowired
    HistoryBrokenMapper historyBrokenMapper;
    @Autowired
    AppealLogMapper appealLogMapper;
    @Autowired
    DtuMapper dtuMapper;
    @Autowired
    ConsumerMapper consumerMapper;
    @Autowired
    ConsumerDtuHistoryMapper consumerDtuHistoryMapper;

    public static final Integer pageSize = 100;

    /**
     *   修复数据，执行一次后删除
     */
    @XxlJob("repairDataJob")
    public ReturnT<String> repairDataJob(String param) {
        XxlJobLogger.log("XXLJOB-repairDataJob start..." );
        log.info("repairDataJob--start--------");
        String key = Constants.EQUIPMENT_CREATE_SERVICE_INFO;
        try {
            Boolean acquire = redisUtil.setIfAbsent(key, String.valueOf(System.currentTimeMillis()), Constants.TIME_OUT);//15分钟超时
            if (acquire) {
                try {
                    execute();
                    return ReturnT.SUCCESS;
                } catch (Exception e) {
                    log.info("repairDataJob-error:{}", e);
                } finally {
                    redisUtil.del(key);
                }
            }
        } catch (Exception e) {
            log.info("repairDataJob-error:{}", e);
        }
        log.info("repairDataJob--end--------");
        XxlJobLogger.log("XXLJOB-repairDataJob end..." );
        return ReturnT.SUCCESS;
    }

    private boolean execute() {
        // 修复客户设备总数
        LambdaQueryWrapper<ConsumerDtuHistory> consumerDtuHistoryQueryWrapper = new LambdaQueryWrapper<>();
        consumerDtuHistoryQueryWrapper.gt(ConsumerDtuHistory::getCreatedAt, "2024-03-21 22:00:00");
        List<ConsumerDtuHistory> consumerDtuList = consumerDtuHistoryMapper.selectList(consumerDtuHistoryQueryWrapper);
        List<Integer> repeatConsumerIds = new ArrayList<>();
        log.info("consumerDtuList.size:{}", consumerDtuList.size());
       // List<Integer> consumerIds = dtuList.stream().map(Dtu::getConsumerId).distinct().collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(consumerDtuList)) {
            for (ConsumerDtuHistory dtu : consumerDtuList) {
                if (!repeatConsumerIds.contains(dtu.getConsumerId()) && dtu.getConsumerId() > 0) {
                    repeatConsumerIds.add(dtu.getConsumerId());
                    LambdaUpdateWrapper<Consumer> consumerUpdateWrapper = new LambdaUpdateWrapper<>();
                    consumerUpdateWrapper.eq(Consumer::getId,dtu.getConsumerId()).eq(Consumer::getIsDeleted,0);
                    Consumer consumer = new Consumer();
                    QueryWrapper<Dtu> dtu1QueryWrapper = new QueryWrapper<>();
                    dtu1QueryWrapper.lambda().like(Dtu::getIMEI, "-")
                            .eq(Dtu::getConsumerId, dtu.getConsumerId())
                            .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                            .eq(Dtu::getSpId, dtu.getSpId());
                    Integer pointTotal = dtuMapper.selectCount(dtu1QueryWrapper);
                    consumer.setPointTotal(pointTotal);
                    QueryWrapper<Dtu> dtu2QueryWrapper = new QueryWrapper<>();
                    dtu2QueryWrapper.lambda().eq(Dtu::getConsumerId, dtu.getConsumerId())
                            .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                            .eq(Dtu::getSpId, dtu.getSpId());
                    Integer allTotal = dtuMapper.selectCount(dtu2QueryWrapper);
                    consumer.setEquipmentTotal(allTotal - pointTotal);
                    consumerMapper.update(consumer, consumerUpdateWrapper);
                }
            }
        }


        // 报警信息修复
        LambdaQueryWrapper<AppealLog> appealLogQueryWrapper = new LambdaQueryWrapper<>();
        List<String> list = new ArrayList();
        list.add("安装调试");
        list.add("工单调试");
        appealLogQueryWrapper.in(AppealLog::getUserName, list)
                 .gt(AppealLog::getUpdatedAt, "2024-03-22 08:00:00")
                 .eq(AppealLog::getIsDeleted, IS_DELETED_FALSE);
        List<AppealLog> appealLogList = appealLogMapper.selectList(appealLogQueryWrapper);
        log.info("appealLogList.size:{}", appealLogList.size());
        if (CollectionUtils.isNotEmpty(appealLogList)) {
            for (AppealLog appealLog : appealLogList) {
                LambdaUpdateWrapper<HistoryAlarm> historyAlarmWrapper = new LambdaUpdateWrapper<>();
                historyAlarmWrapper.eq(HistoryAlarm::getId,appealLog.getAlarmBrokenId()).eq(HistoryAlarm::getIsDeleted,0);
                HistoryAlarm historyAlarm = new HistoryAlarm();
                historyAlarm.setWorkorderId(appealLog.getWorkorderId() == null ? 0L : appealLog.getWorkorderId());
                historyAlarm.setAppealStatus(appealLog.getAppealStatus());
                historyAlarm.setAppealResult(appealLog.getAppealResult());
                historyAlarm.setUserName(appealLog.getUserName());
                historyAlarm.setUserAccount(appealLog.getUserAccount());
                historyAlarm.setAppealTime(appealLog.getCreatedAt());
                historyAlarmMapper.update(historyAlarm, historyAlarmWrapper);
            }
        }


        return true;
    }



}